import { getLyric, getSongsUrl } from 'api/song'
import { ERR_OK } from 'api/config'
import { Base64 } from 'js-base64'// 歌词转码

// ES6构造函数写法
export default class Song {
  constructor ({ id, mid, singer, name, album, duration, image, url }) {
    this.id = id
    this.mid = mid
    this.singer = singer
    this.name = name
    this.album = album
    this.duration = duration
    this.image = image
    this.url = url
  }

  // ES6构造函数写法 可以直接添加方法
  // 扩展一个方法
  // getLyric () {
  //   getLyric(this.mid)
  //     .then((result) => {
  //       if (result.retcode === ERR_OK) {
  //         // 给一个歌词属性
  //         this.lyric = result.lyric
  //         console.log(result)
  //       }
  //     })
  // }
}

// 获取歌词   实例对象可以调用原型对象上的方法
Song.prototype.getLyric = function () {
  // 在 currentSong 变化的时候就回去调用 getLyric
  // 判断如果有 lyric 就直接返回
  if (this.lyric) {
    return Promise.resolve(this.lyric)
  }

  return new Promise((resolve, reject) => {
    getLyric(this.mid)
      .then((result) => {
        if (result.retcode === ERR_OK) {
          this.lyric = Base64.decode(result.lyric)
          resolve(this.lyric)
        } else {
          // eslint-disable-next-line
          reject('no lyric')
        }
      })

      .catch((error) => {
        console.log(error)
      })
  })
}

export function createSong (musicData) {
  return new Song({
    id: musicData.songid,
    mid: musicData.songmid,
    singer: filterSinger(musicData.singer),
    name: musicData.songname,
    album: musicData.albumname,
    duration: musicData.interval,
    image: `https://y.gtimg.cn/music/photo_new/T002R300x300M000${musicData.albummid}.jpg?max_age=2592000`,
    url: musicData.url
  })
}

function filterSinger (singer) {
  if (!singer) {
    return ''
  } else {
    let list = singer.map((item, index) => {
      return item.name
    })

    return list.join('/')
  }
}

export function isValidMusic (musicData) {
  return musicData.songid && musicData.albummid && (!musicData.pay || musicData.pay.payalbumprice === 0)
}

export function processSongsUrl (songs) {
  if (!songs.length) {
    return Promise.resolve(songs)
  }
  return getSongsUrl(songs).then((purlMap) => {
    songs = songs.filter((song) => {
      const purl = purlMap[song.mid]
      if (purl) {
        song.url = purl.indexOf('http') === -1 ? `http://dl.stream.qqmusic.qq.com/${purl}` : purl
        return true
      }
      return false
    })
    return songs
  })
}
